package cl.uchile.sketchpad.services;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import cl.uchile.sketchpad.persistance.dao.UploadedFileDao;
import cl.uchile.sketchpad.persistance.model.UploadedFile;

@Service
public class UploadedFileServiceImpl implements UploadedFileService {
	
	private static final Logger LOG = LoggerFactory.getLogger(UploadedFileServiceImpl.class);
	
	@Autowired
	private UploadedFileDao uploadedFileDao;

	@Override
	@Transactional(readOnly = true)
	public List<UploadedFile> getAll() {
		return this.uploadedFileDao.getAll();
	}

	@Override
	@Transactional(readOnly = true)
	public UploadedFile findById(Long id) {
		return this.uploadedFileDao.findById(id);
	}

	@Override
	@Transactional
	public void persist(UploadedFile uploadedFile) {
		this.uploadedFileDao.persist(uploadedFile);
	}

	@Override
	@Transactional
	public void remove(UploadedFile uploadedFile) {
		this.uploadedFileDao.remove(uploadedFile);
	}
	
	@Override
	@Transactional
	public UploadedFile saveFile(MultipartFile file) {
		UploadedFile res = null;
		
		if ( file == null || file.getSize() <= 0 )
			throw new IllegalArgumentException("file can't be null or be an empty file");
		
		try {
			res = new UploadedFile( 
				file.getOriginalFilename(), 
				file.getContentType(),
				Base64.encodeBase64String(file.getBytes()));
			this.persist(res);
		} catch ( Exception e ) {
			e.printStackTrace(System.err);
			LOG.error(e.toString(), e);
		}
			
		return res;
	}

	@Override
	@Transactional
	public List<UploadedFile> saveFiles(List<MultipartFile> files) {
		if ( files == null || files.size() <= 0 )
			throw new IllegalArgumentException("the array of files to save can't be empty or null");

		List<UploadedFile> res = new ArrayList<UploadedFile>(files.size());
		
		for ( MultipartFile file : files )
			if ( file != null && file.getSize() > 0 )
				res.add(this.saveFile(file));
		
		return res;
	}

}
